<?php

use App\Jobs\TestJob;
use App\Jobs\UserInit;
use App\Models\AdminPermission;
use App\Models\Cashbook;
use App\Models\Cashflow;
use App\Models\Category;
use App\Models\Member;
use App\Models\Mplogin;
use App\Notifications\SysNotify;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;

/**
 * 同步到权限表
 */
Artisan::command('sync:permission', function () {
    $names = array_keys(\Illuminate\Support\Facades\Route::getRoutes()->getRoutesByName());
    foreach ($names as $name) {
        if (strstr($name, 'generated') !== false) {
            continue;
        }
        AdminPermission::query()->firstOrCreate(['tag' => $name], ['name' => $name,]);
    }
    Artisan::call('iseed', ['tables' => 'admin_permissions'], $this->output);
});


Artisan::command('test:UserInit', function () {
    UserInit::dispatchSync(1);
});

Artisan::command('test:queue', function () {
    TestJob::dispatch();
});

Artisan::command('restart', function () {
    Artisan::call('optimize:clear', [], $this->output);
    Artisan::call('optimize', [], $this->output);
    Artisan::call('queue:restart', [], $this->output);
});

Artisan::command('test:notify', function () {
    $user = Member::query()->find(54324);
    $user->notify(new SysNotify('这是测试消息', '测试内容', '这里是子标题'));
});

Artisan::command('sync:clear', function () {
    // 清理登录
    $data =  Mplogin::query()->with('user')->get();
    $this->info('mplogins:' . $data->count());
    foreach ($data as $mp) {
        if (is_null($mp->user)) {
            $mp->delete();
            $this->info('清理:mplogins');
        }
    }

    // 清理分类
    $data = Category::query()->with('user')->get();
    $this->info('category:' . $data->count());
    foreach ($data as $c) {
        if ($c->user_id != 0 && is_null($c->user)) {
            $c->delete();
            $this->info('清理:category');
        }
    }

    // 清理账单
    $data = Cashflow::query()->with('user')->get();
    $this->info('cashflow:' . $data->count());
    foreach ($data as $c) {
        if (is_null($c->user)) {
            $c->delete();
            $this->info('清理:cashflow');
        }
    }

    // 清理账单
    $data = Cashbook::query()->with('user')->get();
    $this->info('Cashbook:' . $data->count());
    foreach ($data as $c) {
        if (is_null($c->user)) {
            $c->delete();
            $this->info('清理:Cashbook');
        }
    }
});
